package cn.touna.jss.common.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 解析http 请求头和请求体工具类
 */

public class HttpParseUtil {

    private static final Logger logger = LogManager.getLogger(HttpParseUtil.class);

    /**
     * 获取http请求头部信息
     *
     * @param request
     * @return
     * @author ljp
     */

    public static Map<String, String> getHeadersInfo(HttpServletRequest request) {
        Map<String, String> map = new HashMap<String, String>();
        if (null == request) {
            return map;
        }
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }


    /**
     * 获取http请求头部信息
     *
     * @param request
     * @return
     * @author ljp
     */

    public static String getParmater(HttpServletRequest request, String parameterName) {
        return request.getParameter(parameterName);

    }


    /**
     * 获取请求参数
     *
     * @param request
     * @return
     */

    public static String getParamString(HttpServletRequest request) {
        StringBuilder param = new StringBuilder();
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream(), JssConstant.CHARACTER_ENCODE));
            String line = bufferedReader.readLine();
            while (null != line) {
                param.append(line);
                line = bufferedReader.readLine();
            }
        } catch (Exception e) {
            logger.info("【解析JSON参数】异常，msg:{}", e.getMessage());
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return param.toString();
    }


}
